<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

require_once APPPATH . 'controllers/main.php';

/**
 * Контроллер поиска по активным страницам
 *
 * @package CoreFramework
 * @version 1.0
 * @author Gennadiy Kozlenko
 */
class Search extends Main {
     
    /**
     * Поисковый запрос
     *
     * @access private
     * @var string
     */
    var $_query = '';
     
    /**
     * Номер страницы
     *
     * @access private
     * @var integer
     */
    var $_page = 1;
     
    /**
     * Количество результатов на страницу
     *
     * @access private
     * @var integer
     */
    var $_per_page = 10;
     
    /**
     * Массив найденых результатов
     *
     * @access private
     * @var array
     */
    var $_search_results = array();
     
    /**
     * Общее количество результатов поиска
     *
     * @access private
     * @var integer
     */
    var $_all_count = 0;
     
    /**
     * Конструктор класса
     *
     * @access public
     * @return Search
     */
    function Search() {
        parent::Main();
        if (false !== $this->input->get('s')) {
            $this->_query = $this->input->get('s');
        }
        if (false !== $this->input->get('page')) {
            $this->_page = (int) $this->input->get('page');
            $this->_page = 1 < $this->_page ? $this->_page : 1;
        }
        $this->load->language('search');
    } // end Search
     
    /**
     * Метод по умолчанию
     *
     * @access public
     */
    function index() {
        $pagination = '';
        if (!empty($this->_query)) {
            // Подгружаем результаты
            $this->_load_results();
            if ($this->_all_count > count($this->_search_results)) {
                $this->load->helper('link');
                $this->load->library('pagination');
                $this->pagination->set_page($this->_page);
                $this->pagination->set_num_pages(ceil($this->_all_count / $this->_per_page));
                $this->pagination->set_url(create_link($this->get_controller(), $this->get_method(), array('page' => '{%page%}', 's' => urlencode($this->_query))));
                $pagination = $this->pagination->create_links();
            }
        }

        $content = '';
        if (0 < count($this->_search_results)) {
            $d = array(
                'results' => $this->_search_results,
                'pagination' => $pagination
            );
            $content = $this->parser->parse('search/results.html', $d, true);
        } else {
            $content = $this->parser->parse('search/no_results.html', array(), true);
        }

        $title = sprintf($this->lang->line('search_title'), htmlspecialchars($this->_query));
        $this->set_metadata('search', htmlspecialchars($this->_query));
        $this->add_param('query', htmlspecialchars($this->_query));

        $data = array(
            'title'   => $title,
            'content' => $content
        );
        $this->set_content($this->parser->parse('search/body.html', $data, true));
        $this->display();
    } // end index
     
    /**
     * Процесс поиска
     *
     * @access private
     */
    function _load_results() {
        $this->benchmark->mark('load_results_start');
        // Бъем поисковый запрос на поисковые термы
        $terms = array_unique(preg_split('~\s+~u', preg_replace('~[^a-zа-я0-9 ]~iu', ' ', $this->_query)));
        foreach ($terms as $id => $term) {
            if (3 > mb_strlen($term, $this->config->item('charset'))) {
                unset($terms[$id]);
            }
        }
        if (0 < count($terms)) {
            $this->load->model('m_search_videos');
            $this->m_search_videos->set_terms($terms);
            $this->m_search_videos->initialize();
            $this->m_search_videos->set_limit($this->_per_page, ($this->_page - 1) * $this->_per_page);
            $this->m_search_videos->load_results();
            if (0 < $this->m_search_videos->get_count()) {
                $this->_all_count = $this->m_search_videos->get_all_count();
                $this->load->helper('content');
                $this->load->helper('thumbnail');
                foreach ($this->m_search_videos->get_results() as $video) {
                    // Получаем описание
                    $video['description'] = strip_tags($video['description']);
                    $title = $video['title'];
                    $orig_title = $video['orig_title'];
                    $description = get_abstract($video['description'], 200);
                    $video['title'] = $title;
                    $video['orig_title'] = $orig_title;
                    $video['description'] = $description;
                    if (!empty($video['image'])) {
                        $this->load->helper('thumbnail');
                        $video['image'] = base_url() . create_thumbnail($video['image'], 80, 120);
                    } else {
                        $video['image'] = base_url() . 'images/search_no_image.jpg';
                    }
                    foreach ($video as $key => $val) {
                        if (empty($val)) {
                            $video['show_' . $key] = array();
                        }
                    }
                    array_push($this->_search_results, $video);
                }
            }
        }
        $this->benchmark->mark('load_results_end');
    } // end load_results

}
